//
//  SingerHeaderController.m
//  A段项目音乐播放
//
//  Created by 太阳 on 15/5/23.
//  Copyright (c) 2015年 lanou3g.com蓝鸥科技. All rights reserved.
//

#import "SingerHeaderController.h"
#import "singerSongCell.h"
#import <AFNetworking/AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "SingerModel.h"
#import "singerSongTableview.h"
#import "myButton.h"
#import "singerproductionCell.h"
#import "PendulumView.h"

@interface SingerHeaderController ()<UITableViewDataSource, UITableViewDelegate, changecellheight>
@property (nonatomic, retain) NSIndexPath *index;
@property (nonatomic ,retain) PendulumView *pendulum;
@end

@implementation SingerHeaderController

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (void)dealloc
{

    [_index release];
    [_pendulum release];
    [_modelarray release];
    [_name release];

//    [_modelarray release];

    [_mytableview release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIColor *ballColor = [UIColor colorWithRed:0.47 green:0.60 blue:0.89 alpha:1];
    self.pendulum = [[PendulumView alloc] initWithFrame:self.view.bounds ballColor:ballColor];
    
    self.navigationItem.title = self.name;
    
    [self.mytableview addSubview:self.pendulum];
    [self builttableview];
   
    [self requestnet];

}
- (void)builttableview
{
    self.mytableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    self.mytableview.dataSource  = self;
    self.mytableview.delegate = self;
    [self.mytableview registerClass:[singerSongCell class] forCellReuseIdentifier:@"cell"];
    [self.mytableview registerClass:[singerproductionCell class] forCellReuseIdentifier:@"cellcell"];
    [self.view addSubview:self.mytableview];
    
    self.state = EnumOfStateNo;
}
- (void)requestnet
{
    NSString *str = [NSString stringWithFormat:@"http://v1.ard.tj.itlily.com/ttpod?a=getnewttpod&id=%ld&size=1000&page=1&app=ttpod&v=v7.9.1.2015050518&uid=&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=826886cd55c251bacd39b2d6523c12b126f3c590&idfa=27D84D88-B1C6-4173-B7C5-EE78CD26E7FB&utdid=VVrl99FV5JUDAA1STsAtAkrx&alf=201200&bundle_id=com.ttpod.music", self.num];
    NSString * str1 = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    str = str1;
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manger GET:str parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        self.modelarray = [NSMutableArray array];
        NSData *data = [NSData dataWithData:responseObject];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", dic);
        NSArray *array = [dic objectForKey:@"data"];
        for (NSDictionary *modeldic in array) {
            SingerModel *model = [[[SingerModel alloc]init] autorelease];
            
            [model setValuesForKeysWithDictionary:modeldic];
            [self.modelarray addObject:model];
        }
        [self.mytableview reloadData];
        [self.pendulum removeFromSuperview];

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

//点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击");
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.modelarray];
    NSLog(@"index.row = %ld", indexPath.row);
    
    NSInteger i = 0;
    NSInteger j = 0;
    for (id model in self.modelarray) {  //如果是这个model类的话
        if (![model isKindOfClass:[SingerModel class]]) {
            //            [array removeObject:model];
            j = i;
        }
        i++;
    }
    SingerModel *model = [array objectAtIndex:indexPath.row];
    if (indexPath.row == j && j != 0) {
        NSLog(@"点击");
        NSLog(@"%ld", indexPath.row);
        NSLog(@"%ld", j);
    } else if( (indexPath.row == j && j == 0) || indexPath.row != j ){
        if (indexPath.row > j) {
            model = [array objectAtIndex:indexPath.row ];
        }
        NSLog(@"j = %ld", j);
        singerSongTableview *table = [[singerSongTableview alloc]init];
        [self.navigationController pushViewController:table animated:YES];
        table.num = [model.singer_id integerValue];
        NSLog(@"table.num = %ld", table.num);
        
        [table release];
    }
}


//- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
//{
//
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelarray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.modelarray objectAtIndex:indexPath.row] isKindOfClass:[SingerModel class]] ) {
        SingerModel *model = [self.modelarray objectAtIndex:indexPath.row];
        singerSongCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.singername.text = model.singerName;
        NSString *str = model.singerName;
        NSDictionary *dic17 = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
        CGRect rect = [str boundingRectWithSize:CGSizeMake(0, 1000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic17 context:nil];
        cell.singername.frame = CGRectMake(80, 8, rect.size.width, 30);
        [cell.photoimage sd_setImageWithURL:[NSURL URLWithString:model.pic_url] placeholderImage:nil options:SDWebImageRetryFailed];
        cell.mybutton.row = indexPath.row;
        cell.mybutton.section = indexPath.section;
        cell.delegate = self;
        [cell.mybutton addTarget:self action:@selector(cellaction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    } else
    {
        SingerModel *model = [[[SingerModel alloc]init] autorelease];
        model = [self.modelarray objectAtIndex:indexPath.row - 1];
        singerproductionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellcell"];
        NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%@/songs?page=1&size=50&app=ttpod&v=v7.9.1.2015050518&uid=&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=826886cd55c251bacd39b2d6523c12b126f3c590&idfa=27D84D88-B1C6-4173-B7C5-EE78CD26E7FB&utdid=VVrl99FV5JUDAA1STsAtAkrx&alf=201200&bundle_id=com.ttpod.music", model.singer_id];
        NSString *address = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
        manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manger GET:address parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSData *data =[NSData dataWithData:responseObject];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = [dic objectForKey:@"data"];
            NSDictionary *dics = [array objectAtIndex:0];
            cell.namelabel.text = [dics objectForKey:@"name"];
            
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"%@", error);
        }];
        //
        //        cell.textLabel.text = @"插入";
        
        return cell;
    }
    //
    //    return nil;
    
    
    
}

//按钮点击事件
- (void)cellaction:(myButton *)btn
{
    
    int i = 0;
    int j = 0;
    NSMutableArray *array = [NSMutableArray array];
    for (id model in self.modelarray) {
        i++;
        if (![model isKindOfClass:[SingerModel class]]) {
            [array addObject:model];
            j = i;
        }
    }
    
    if (self.state == EnumOfStateYes && btn.row == j - 2) {
        [self.modelarray removeObjectsInArray:array];
        [self.mytableview reloadData];
        self.state = EnumOfStateNo;
    } else
        
        if (self.state == EnumOfStateNo) {
            NSArray *array = [NSArray array];
            [self.modelarray insertObject:array atIndex:btn.row+1];
            //    [self.modelarray addObject:array];
            NSLog(@"--------------%@", self.modelarray);
            [self.mytableview insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:btn.row+1 inSection:btn.section]] withRowAnimation:UITableViewRowAnimationMiddle];
            self.state = EnumOfStateYes;
        } else if (self.state == EnumOfStateYes)
        {
            NSMutableArray *array = [NSMutableArray array];
            int i = 0;
            int j = 0;
            for (id model in self.modelarray) {
                if (![model isKindOfClass:[SingerModel class]]) {
                    j = i;
                    [array addObject:model];
                }
                i++;
            }
            [self.modelarray removeObjectsInArray:array];
            [self.mytableview reloadData];
            if ( btn.row <= j) {
                [self.modelarray insertObject:array atIndex:btn.row+1];
                
            } else if (btn.row > j)
            {
                [self.modelarray insertObject:array atIndex:btn.row];
            }
            
            NSLog(@"------  §--------%@", self.modelarray);
            [self.mytableview insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:btn.row+1 inSection:btn.section]] withRowAnimation:UITableViewRowAnimationMiddle];
            self.state = EnumOfStateYes;
        }
    
    
    //    [self.mytableview reloadData];
    NSLog(@"wo");
}

@end
